<template>
  <div class="table-designer h-full flex flex-col">
    <!-- 顶部工具栏 -->
    <div class="designer-toolbar flex items-center justify-between p-3 bg-gray-50 border-b border-gray-200">
      <div class="toolbar-left flex items-center space-x-2">
        <span class="text-sm font-medium">
          {{ tab.table ? `编辑表: ${tab.table}` : '新建表' }}
        </span>
        <span class="text-sm text-gray-500">
          ({{ tab.database }})
        </span>
        <span v-if="isModified" class="text-xs text-amber-500 ml-2">(已修改)</span>
        <span class="text-xs text-gray-500 ml-2">数据库类型: {{ databaseType }}</span>
      </div>
      
      <div class="toolbar-right flex items-center space-x-2">
        <el-button size="small" @click="saveTable" type="primary" :disabled="!isModified">
          <el-icon><Document /></el-icon>
          保存
        </el-button>
        <el-button size="small" @click="previewSQL">
          <el-icon><View /></el-icon>
          预览SQL
        </el-button>
      </div>
    </div>

    <!-- 加载中或错误状态 -->
    <div v-if="isLoading" class="text-center py-8 flex-1">
        <el-icon class="text-4xl text-gray-400 mb-4 animate-spin"><Loading /></el-icon>
        <p class="text-gray-500">加载表结构中...</p>
    </div>
    <div v-else-if="error" class="text-center py-8 flex-1">
        <el-icon class="text-4xl text-red-400 mb-4"><Warning /></el-icon>
        <p class="text-red-500">{{ error }}</p>
        <el-button size="small" type="primary" class="mt-4" @click="loadTableStructure">重试</el-button>
    </div>

    <!-- 内容区域 -->
    <div v-else class="designer-content flex-1 flex flex-col overflow-hidden">
      <!-- 标签页移至内容区域顶部 -->
      <div class="tab-container bg-white border-b border-gray-200">
        <el-tabs v-model="activeTab" class="designer-tabs">
          <el-tab-pane label="基本信息" name="general"></el-tab-pane>
          <el-tab-pane label="列定义" name="columns"></el-tab-pane>
          <el-tab-pane label="索引" name="indexes"></el-tab-pane>
          <el-tab-pane label="外键约束" name="foreignKeys" v-if="supportsForeignKeys"></el-tab-pane>
          <el-tab-pane label="高级选项" name="advanced" v-if="supportsAdvancedOptions"></el-tab-pane>
          <el-tab-pane label="SQL预览" name="sql"></el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 面板内容 -->
      <div class="panel-content flex-1 overflow-auto p-4">
        <component 
          :is="currentPanel" 
          :columns="tableData.columns"
          :indexes="tableData.indexes"
          :foreign-keys="tableData.foreignKeys"
          :advanced-options="tableData.advancedOptions"
          :table-data="tableData"
          :is-new-table="isNewTable"
          :database-type="databaseType"
          :database-configs="databaseConfigs"
          :connection-id="connectionId"
          @add="handleAdd"
          @remove="handleRemove"
          @update="handleUpdate"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue';
import { Document, View, Loading, Warning } from '@element-plus/icons-vue';
import TableGeneralPanel from './table-designer/TableGeneralPanel.vue';
import TableColumnsPanel from './table-designer/TableColumnsPanel.vue';
import TableIndexesPanel from './table-designer/TableIndexesPanel.vue';
import TableForeignKeysPanel from './table-designer/TableForeignKeysPanel.vue';
import TableAdvancedPanel from './table-designer/TableAdvancedPanel.vue';
import TableSqlPreview from './table-designer/TableSqlPreview.vue';
import { useDBServiceStore } from '@/stores/dbService';
import { useTableStructureStore } from '@/stores/tableStructureStore';
import { ElMessage } from 'element-plus';

const props = defineProps({
  tab: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update']);
const dbServiceStore = useDBServiceStore();
const tableStructureStore = useTableStructureStore();

// 状态管理
const isLoading = ref(false);
const error = ref(null);
const isModified = ref(false);
const activeTab = ref('general');

// 数据库配置信息
const databaseConfigs = ref([]);
const databaseType = computed(() => {
  return props.tab.data?.databaseType || 'mysql';
});

// 兼容不同的属性名（connectionId 和 configId）
const connectionId = computed(() => {
  // 优先使用 connectionId，如果不存在则尝试使用 configId
  return props.tab.connectionId || props.tab.configId;
});

// 根据数据库类型判断是否支持特定功能
const supportsForeignKeys = computed(() => {
  return ['mysql', 'postgresql', 'sqlserver'].includes(databaseType.value);
});

const supportsAdvancedOptions = computed(() => {
  return ['mysql', 'postgresql'].includes(databaseType.value);
});

const isNewTable = computed(() => {
  return props.tab.data?.isNewTable || false;
});

// 表数据
const tableData = ref({
  name: '',
  engine: 'InnoDB',
  charset: 'utf8mb4',
  collation: 'utf8mb4_general_ci',
  comment: '',
  columns: [],
  indexes: [],
  foreignKeys: [],
  advancedOptions: {},
  primaryKey: null
});

// 加载表结构
const loadTableStructure = async () => {
  if (isNewTable.value) {
    initNewTable();
    return;
  }
  
  isLoading.value = true;
  error.value = null;
  
  try {
    // 记录当前尝试加载的表信息，用于调试
    console.log('Attempting to load table structure:', {
      connectionId: connectionId.value,
      database: props.tab.database,
      table: props.tab.table,
      databaseType: databaseType.value
    });
    
    if (!connectionId.value) {
      throw new Error('Missing connection ID. Please specify a valid connection.');
    }
    
    // 加载数据库配置
    await loadDatabaseConfigs();
    
    // 检查配置ID是否有效
    const configExists = databaseConfigs.value.some(c => c.id === connectionId.value);
    if (!configExists) {
      throw new Error(`Connection configuration with ID ${connectionId.value} does not exist`);
    }

    // 加载表结构
    const structure = await tableStructureStore.fetchTableStructure({
      configId: connectionId.value,
      database: props.tab.database,
      table: props.tab.table,
      databaseType: databaseType.value
    });
    
    // 将结构转换为本地格式
    tableData.value = convertToLocalFormat(structure);
    
    // 更新tab数据
    updateTabData();
    
    isModified.value = false;
  } catch (err) {
    console.error('Table structure loading failed:', err);
    error.value = `加载表结构失败: ${err.message || '未知错误'}`;
    ElMessage.error(error.value);
  } finally {
    isLoading.value = false;
  }
};

// 加载数据库配置
const loadDatabaseConfigs = async () => {
  try {
    console.log('Loading database configurations');
    databaseConfigs.value = await dbServiceStore.getAllConfigs();
    console.log('Loaded configurations:', databaseConfigs.value.length);
    
    // 记录配置ID用于调试
    const configIds = databaseConfigs.value.map(c => c.id);
    console.log('Available config IDs:', configIds);
  } catch (err) {
    console.error("加载数据库配置失败:", err);
    throw new Error(`无法加载数据库配置: ${err.message}`);
  }
};

// 初始化新表
const initNewTable = () => {
  // 创建默认的表结构（根据数据库类型定制）
  tableData.value = getDefaultTableStructure(databaseType.value);
  
  // 更新tab数据
  updateTabData();
  
  // 新表默认为已修改状态
  isModified.value = true;
};

// 根据数据库类型获取默认表结构
const getDefaultTableStructure = (dbType) => {
  const defaultStructure = {
    name: props.tab.table || 'new_table',
    comment: '',
    columns: [],
    indexes: [],
    foreignKeys: [],
    advancedOptions: {}
  };
  
  // 添加默认ID列
  const idColumn = {
    name: 'id',
    notNull: true,
    primaryKey: true,
    comment: '主键ID'
  };
  
  // 根据数据库类型添加特定属性
  switch (dbType) {
    case 'mysql':
      defaultStructure.engine = 'InnoDB';
      defaultStructure.charset = 'utf8mb4';
      defaultStructure.collation = 'utf8mb4_general_ci';
      
      idColumn.type = 'int';
      idColumn.length = '11';
      idColumn.autoIncrement = true;
      break;
      
    case 'postgresql':
      idColumn.type = 'serial';
      defaultStructure.schema = 'public';
      break;
      
    case 'sqlite':
      idColumn.type = 'integer';
      idColumn.autoIncrement = true;
      break;
      
    case 'sqlserver':
      idColumn.type = 'int';
      idColumn.identity = true;
      defaultStructure.schema = 'dbo';
      break;
  }
  
  defaultStructure.columns.push(idColumn);
  defaultStructure.primaryKey = 'id';
  
  return defaultStructure;
};

// 保存表结构
const saveTable = async () => {
  if (!validateTable()) {
    return;
  }

  isLoading.value = true;
  error.value = null;
  
  try {
    // 将本地格式转换为API格式
    const apiData = convertToApiFormat(tableData.value);
    
    // 保存到服务器
    const result = await tableStructureStore.saveTableStructure({
      configId: connectionId.value,
      database: props.tab.database,
      table: tableData.value.name,
      structure: apiData,
      isNewTable: isNewTable.value,
      databaseType: databaseType.value
    });
    
    // 显示成功消息
    ElMessage.success(isNewTable.value ? '表创建成功' : '表结构已更新');
    
    // 更新tab数据
    updateTabData({
        lastSaved: new Date().toISOString(),
        isNewTable: false // 保存后不再是新表
    });
    
    isModified.value = false;
  } catch (err) {
    error.value = `保存表结构失败: ${err.message || '未知错误'}`;
    ElMessage.error(error.value);
  } finally {
    isLoading.value = false;
  }
};

// 预览SQL
const previewSQL = () => {
  // 切换到SQL预览标签
  activeTab.value = 'sql';
};

// 验证表数据
const validateTable = () => {
  // 检查表名
  if (!tableData.value.name.trim()) {
    ElMessage.error('请输入表名');
    activeTab.value = 'general';
    return false;
  }
  
  // 检查是否有列
  if (tableData.value.columns.length === 0) {
    ElMessage.error('表至少需要一列');
    activeTab.value = 'columns';
    return false;
  }
  
  // 检查每一列
  for (let i = 0; i < tableData.value.columns.length; i++) {
    const column = tableData.value.columns[i];
    
    if (!column.name.trim()) {
      ElMessage.error(`第 ${i+1} 列名称不能为空`);
      activeTab.value = 'columns';
      return false;
    }
  }
  
  // 检查索引
  for (const index of tableData.value.indexes) {
    if (!index.name.trim()) {
      ElMessage.error('索引名不能为空');
      activeTab.value = 'indexes';
      return false;
    }
    
    if (!index.columns || index.columns.length === 0) {
      ElMessage.error(`索引 ${index.name} 未选择列`);
      activeTab.value = 'indexes';
      return false;
    }
  }
  
  return true;
};

// 添加列
const addColumn = (column) => {
  tableData.value.columns.push(column);
  markAsModified();
};

// 删除列
const removeColumn = (index) => {
    const columnName = tableData.value.columns[index].name;
  
  // 更新索引和外键引用
  removeColumnReferences(columnName);
  
  // 删除列
  tableData.value.columns.splice(index, 1);
  markAsModified();
};

// 移除列的所有引用
const removeColumnReferences = (columnName) => {
        // 从索引中移除该列的引用
        tableData.value.indexes.forEach(idx => {
          idx.columns = idx.columns.filter(col => col !== columnName);
        });
        
  // 删除空索引
        tableData.value.indexes = tableData.value.indexes.filter(idx => idx.columns.length > 0);
        
  // 从外键中移除该列的引用
  tableData.value.foreignKeys = tableData.value.foreignKeys.filter(fk => 
    !fk.columns.includes(columnName)
  );
};

// 添加索引
const addIndex = (index) => {
  tableData.value.indexes.push(index);
  markAsModified();
};

// 删除索引
const removeIndex = (index) => {
    tableData.value.indexes.splice(index, 1);
    markAsModified();
};

// 添加外键
const addForeignKey = (foreignKey) => {
  tableData.value.foreignKeys.push(foreignKey);
  markAsModified();
};

// 删除外键
const removeForeignKey = (index) => {
  tableData.value.foreignKeys.splice(index, 1);
  markAsModified();
};

// 处理表基本信息更新
const handleTableDataUpdate = (updatedData) => {
  Object.assign(tableData.value, updatedData);
  markAsModified();
};

// 处理列更新
const handleColumnsUpdate = (updatedColumns) => {
  // Create a new array to avoid reactivity issues
  tableData.value = {
    ...tableData.value,
    columns: [...updatedColumns]
  };
  markAsModified();
};

// 处理索引更新
const handleIndexesUpdate = (updatedIndexes) => {
  tableData.value.indexes = updatedIndexes;
  markAsModified();
};

// 处理外键更新
const handleForeignKeysUpdate = (updatedForeignKeys) => {
  tableData.value.foreignKeys = updatedForeignKeys;
        markAsModified();
};

// 处理高级选项更新
const handleAdvancedOptionsUpdate = (updatedOptions) => {
  tableData.value.advancedOptions = updatedOptions;
  markAsModified();
};

// 将API数据转换为本地格式
const convertToLocalFormat = (apiData) => {
  // 标准化列信息
  const normalizedColumns = apiData.columns.map(col => {
    return {
      ...col,
      // 确保长度信息正确
      length: col.length || 0,
      lengthDisplay: col.lengthDisplay || '',
      // 确保注释正确
      comment: col.comment || col.Comment || '',
      // 达梦特有属性
      semanticType: col.semanticType || (col.rawInfo ? col.rawInfo.semanticType : '') || 'BYTE'
    };
  });
  
  const localData = {
    name: apiData.name,
    comment: apiData.comment || '',
    columns: normalizedColumns,
    indexes: apiData.indexes || [],
    foreignKeys: apiData.foreignKeys || [],
    advancedOptions: apiData.options || {}
  };
  
  // 根据数据库类型处理特定属性
  if (databaseType.value === 'mysql') {
    localData.engine = apiData.engine || 'InnoDB';
    localData.charset = apiData.charset || 'utf8mb4';
    localData.collation = apiData.collation || 'utf8mb4_general_ci';
  } else if (['postgresql', 'sqlserver'].includes(databaseType.value)) {
    localData.schema = apiData.schema || (databaseType.value === 'postgresql' ? 'public' : 'dbo');
  } else if (databaseType.value === 'dameng') {
    // 达梦特有属性
    localData.charset = apiData.charset || 'UTF8';
    localData.lengthSemantics = apiData.lengthSemantics || 'BYTE';
  }
  
  return localData;
};

// 将本地格式转换为API格式
const convertToApiFormat = (localData) => {
  // 确保列信息包含所有必要属性
  const processedColumns = localData.columns.map(col => {
    const processedCol = {...col};
    
    // 处理达梦特有的语义类型
    if (databaseType.value === 'dameng' && (
        col.type.toLowerCase().includes('char') || 
        col.type.toLowerCase().includes('varchar'))) {
      processedCol.semanticType = col.semanticType || 'BYTE';
    }
    
    return processedCol;
  });
  
  const apiData = {
    name: localData.name,
    comment: localData.comment,
    columns: processedColumns,
    indexes: localData.indexes,
    foreignKeys: localData.foreignKeys,
    options: localData.advancedOptions
  };
  
  // 根据数据库类型添加特定属性
  if (databaseType.value === 'mysql') {
    apiData.engine = localData.engine;
    apiData.charset = localData.charset;
    apiData.collation = localData.collation;
  } else if (['postgresql', 'sqlserver'].includes(databaseType.value)) {
    apiData.schema = localData.schema;
  } else if (databaseType.value === 'dameng') {
    apiData.charset = localData.charset || 'UTF8';
    apiData.lengthSemantics = localData.lengthSemantics || 'BYTE';
  }
  
  return apiData;
};

// 标记为已修改
const markAsModified = () => {
  if (!isModified.value) {
    isModified.value = true;
    
    // 通知父组件数据已修改
    emit('update', {
      unsaved: true
    });
  }
  
  // 更新tab数据
  updateTabData();
};

// 更新tab数据
const updateTabData = (additionalData = {}) => {
  emit('update', {
    data: {
      ...props.tab.data,
      tableName: tableData.value.name,
      databaseType: databaseType.value,
      lastModified: new Date().toISOString(),
      ...additionalData
    }
  });
};

// 当组件挂载时加载表结构
onMounted(() => {
  loadTableStructure();
});

// 监听tab数据变化
watch(() => props.tab.data, (newData) => {
  if (newData && newData.tableName) {
    // 从tab数据恢复状态
      tableData.value.name = newData.tableName;
  }
}, { deep: true });

// 计算当前应该显示的面板组件
const currentPanel = computed(() => {
  switch (activeTab.value) {
    case 'general':
      return TableGeneralPanel;
    case 'columns':
      return TableColumnsPanel;
    case 'indexes':
      return TableIndexesPanel;
    case 'foreignKeys':
      return TableForeignKeysPanel;
    case 'advanced':
      return TableAdvancedPanel;
    case 'sql':
      return TableSqlPreview;
    default:
      return TableGeneralPanel;
  }
});

// 统一的事件处理方法
const handleAdd = (item) => {
  switch (activeTab.value) {
    case 'columns':
      addColumn(item);
      break;
    case 'indexes':
      addIndex(item);
      break;
    case 'foreignKeys':
      addForeignKey(item);
      break;
  }
};

const handleRemove = (index) => {
  switch (activeTab.value) {
    case 'columns':
      removeColumn(index);
      break;
    case 'indexes':
      removeIndex(index);
      break;
    case 'foreignKeys':
      removeForeignKey(index);
      break;
  }
};

const handleUpdate = (data) => {
  switch (activeTab.value) {
    case 'general':
      handleTableDataUpdate(data);
      break;
    case 'columns':
      handleColumnsUpdate(data);
      break;
    case 'indexes':
      handleIndexesUpdate(data);
      break;
    case 'foreignKeys':
      handleForeignKeysUpdate(data);
      break;
    case 'advanced':
      handleAdvancedOptionsUpdate(data);
      break;
  }
};
</script>

<style scoped>
.table-designer {
  background-color: #f9fafb;
  height: 100%;
}

.designer-toolbar {
  border-bottom: 1px solid #e5e7eb;
  padding: 0.75rem 1rem;
}

.tab-container {
  background-color: white;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.designer-tabs {
  --el-tabs-header-height: 48px;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
  padding: 0 1rem;
  border-bottom: none;
}

:deep(.el-tabs__nav) {
  border-bottom: none !important;
}

:deep(.el-tabs__item) {
  height: 48px;
  line-height: 48px;
  font-size: 14px;
  font-weight: 500;
  color: #4b5563;
  transition: all 0.2s ease;
}

:deep(.el-tabs__item:hover) {
  color: #3b82f6;
}

:deep(.el-tabs__item.is-active) {
  color: #3b82f6;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #3b82f6;
  height: 3px;
  border-radius: 3px;
}

.panel-content {
  padding: 1rem;
  background-color: white;
  border-radius: 0 0 4px 4px;
  height: calc(100% - 48px);
}
</style> 